<?php

namespace App\Service\Third;

use App\Helpers\PayUtil;
use App\Helpers\RedisUtil;
use App\Model\PaycallbackLog;
use App\Model\PayOrder;
use App\Model\Service\PaycallbackService;

/**
 * 微信支付回调
 */
class WechatPayCallbackService extends PayBaseService
{
    public function handle()
    {
        $payNotify = new WechatPayNotify;
        $payNotify->swooleRequest = $this->request;
        $payNotify->swooleResponse = $this->response;
        //获取回调数据
        $callbackArray = $payNotify->getNotifyData();
        // log_info(__CLASS__ . "==" . json_encode($callbackArray));
        //订单号
        $outTradeNo = $this->parseOutTradeNo($callbackArray);

        //锁住该订单处理
        $lockTime = 120;
        $key = "WechatPayCallbackService_{$outTradeNo}";
        if (RedisUtil::concurrentLock($key, $lockTime)) {
            log_info(__CLASS__ . "==LastProcessing=={$outTradeNo}");
            return ['result' => 1];
        }

        //记录回调日志
        PaycallbackLog::addRecord(PayOrder::CHANNEL_WX, $outTradeNo, $callbackArray);

        $sdk = new \Yurun\PaySDK\Weixin\SDK(PayUtil::wechatPublicParams($callbackArray['mch_id']));
        try {
            $sdk->notify($payNotify);
            log_info(__CLASS__ . "==Success=={$outTradeNo}");
            //支付回调
            $payMoney = $this->parsePayMoney($callbackArray);
            PaycallbackService::successCallback($outTradeNo, $payMoney, PayOrder::CHANNEL_WX);
        } catch (\Exception $e) {
            log_info(__CLASS__ . "==Fail=={$outTradeNo}");
        }
    }

    /**
     * 解析支付订单号
     */
    protected function parseOutTradeNo($callbackArray = [])
    {
        return $callbackArray['out_trade_no'] ?? '';
    }

    /**
     * 解析支付总金额（分）
     */
    protected function parsePayMoney($callbackArray = [])
    {
        return $callbackArray['total_fee'] ?? 0;
    }
}
